package com.anstudio.app.lhasa.core.daos;

import com.anstudio.app.lhasa.core.untils.SqlUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseDao {

    private static Map<String, BaseDao> registryMap = new HashMap();

    protected final static String DEFAULT_KEY = "batis_config.xml";

    protected SqlSession session = null;

    protected String key;

    protected void startSession() {
        endSession();
        session = SqlUtils.instance.getSqlSessionFactory(key).openSession();
    }

    protected void endSession() {
        if (session != null) {
            session.close();
        }
    }

    protected void updateKey(String key) {
        this.key = key;
    }

    public static <T extends BaseDao> T getDao(final Class<T> clazz, String key) {
        T ret = null;

        if (clazz == null) {
            return null;
        }

        try {
            String className = clazz.getName();
            if (!registryMap.containsKey(className)) {
                synchronized (registryMap) {
                    ret = clazz.newInstance();
                    if (ret != null) {
                        registryMap.put(className, ret);
                    }
                }
            } else {
                ret = (T)registryMap.get(className);
            }

            ret.updateKey(key);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            return ret;
        }
    }

    public abstract Object getObjectById(int id);
}
